#!/usr/bin/env php
<?php
function main($argv)
{
    if(isset($argv[1]))
        $conn=oci_connect('dbuser', 'dbuser', $argv[1]);
    else
        $conn=oci_connect('dbuser', 'dbuser', 'localhost');
    if($conn === false)
    {
        $error=oci_error();
        printf("connect to db fail: %d %s\n",
                $error['code'], $error['message']);
        return 1;
    }

    $stmt=oci_parse($conn,
            "select empno,to_char(update_ts,'YYYYMMDDHH24MISS'),".
            "name,age ".
            "from my_emp where empno<:empno");
    if($stmt === false)
    {
        $error=oci_error($conn);
        printf("prepare fail: %d %s\n",
                $error['code'], $error['message']);
        return 1;
    }
    $empno=5;
    oci_bind_by_name($stmt, ':empno', $empno);
    if(oci_execute($stmt) == false)
    {
        $error=oci_error($stmt);
        printf("execute fail: %d %s\n",
                $error['code'], $error['message']);
        return 1;
    }
    while($row=oci_fetch_array($stmt, OCI_NUM))
    {
        printf("%d %s %s %d\n", $row[0], $row[1], $row[2], $row[3]);
    }
    oci_free_statement($stmt);
    print "----------------------------------------\n";

    $stmt=oci_parse($conn,
            "update my_emp set update_ts=sysdate,age=:age ".
            "where empno=:empno");
    $age=30;
    oci_bind_by_name($stmt, ':age', $age);
    $empno=1;
    oci_bind_by_name($stmt, ':empno', $empno);
    if(oci_execute($stmt, OCI_DEFAULT) == false)
    {
        $error=oci_error($stmt);
        printf("update fail: %d %s\n",
                $error['code'], $error['message']);
        oci_rollback($conn);
        return 1;
    }
    if(oci_num_rows($stmt) == 0)
        printf("update no row\n");
    else
        printf("update succeed\n");
    oci_free_statement($stmt);
    oci_commit($conn);
    print "----------------------------------------\n";

    $stmt=oci_parse($conn, "insert into my_emp values(".
            ":empno,sysdate,:name,:duty,:age,:address)");
    $empno=100;
    oci_bind_by_name($stmt, ':empno', $empno);
    $name='壮东风';
    oci_bind_by_name($stmt, ':name', $name);
    $duty='1';
    oci_bind_by_name($stmt, ':duty', $duty);
    $age=30;
    oci_bind_by_name($stmt, ':age', $age);
    $address='上海南京西路100号';
    oci_bind_by_name($stmt, ':address', $address);
    if(oci_execute($stmt, OCI_DEFAULT) == false)
    {
        $error=oci_error($stmt);
        oci_free_statement($stmt);
        if($error['code'] == 1)
        {
            printf("insert empno(%d) duplicate\n", $empno);
        }
        else
        {
            printf("insert fail: %d %s\n",
                    $error['code'], $error['message']);
        }
        oci_rollback($conn);
        return 1;
    }
    oci_free_statement($stmt);
    oci_commit($conn);
    print "insert succeed\n";
    print "----------------------------------------\n";

    oci_close($conn);

    return 0;
}

main($argv);
?>
